import { ref, onMounted, onBeforeUnmount } from 'vue'
import { debounce } from 'lodash-es'

export function useTableHeight(containerSelector = '.app-container', formSelector = '.search-form', offset = 140) {
  const tableHeight = ref(0)

  const calculateTableHeight = debounce(() => {
    const container = document.querySelector(containerSelector)
    const form = document.querySelector(formSelector)
    if (container) {
      const containerHeight = container.offsetHeight || 0
      const formHeight = form?.offsetHeight || 0
      tableHeight.value = containerHeight - formHeight - offset
    }
  }, 200)

  onMounted(() => {
    calculateTableHeight()
    window.addEventListener('resize', calculateTableHeight)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', calculateTableHeight)
  })

  return { tableHeight, calculateTableHeight }
}
